<template>
  <div class="flex">
    <el-button
      size="small"
      type="primary"
      :plain="!like.state"
      @click="vote('like')"
      :loading="loading.like"
    >
      <svg-icon v-show="!loading.like" icon-name="like-fill" />
      {{ like.tip }} {{ like.count }}
    </el-button>
    <el-button
      size="small"
      type="primary"
      :plain="!dislike.state"
      @click="vote('dislike')"
      :loading="loading.dislike"
    >
      <svg-icon v-show="!loading.dislike" icon-name="dislike-fill" />
      {{ dislike.count }}
    </el-button>
    <el-button
      size="small"
      type="success"
      :plain="!collect.state"
      @click="vote('collect')"
      :loading="loading.collect"
      class="m-l-16"
    >
      <svg-icon v-show="!loading.collect" icon-name="star-fill" />
      {{ collect.tip }}
    </el-button>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import { formatResource } from '../format';

export default {
  name: 'vote-buttons',
  data() {
    return {
      loading: {
        like: false,
        dislike: false,
        collect: false,
      },
    };
  },
  computed: {
    ...mapState({ curDoc: 'currentDocument' }),
    like() {
      const isLiked = this.curDoc.voteStates.like;
      return {
        state: isLiked,
        tip: isLiked ? '已点赞' : '点赞',
        count: this.curDoc.voteCounts.like,
      };
    },
    dislike() {
      const isDisliked = this.curDoc.voteStates.dislike;
      return {
        state: isDisliked,
        count: this.curDoc.voteCounts.dislike,
      };
    },
    collect() {
      const isCollected = this.curDoc.voteStates.collect;
      return {
        state: isCollected,
        tip: isCollected ? '已收藏' : '收藏',
      };
    },
  },
  methods: {
    ...mapActions(['setCurrentDocument']),
    // 点赞、点踩（或取消）
    vote(action) {
      this.loading[action] = true;
      const voteParams = this.voteParams(action); // 后面两次用到
      this.$api.other.vote(voteParams)
        .then((res) => {
          this.setCurrentDocument(formatResource(res.data)); // 更新资源数据
          this.$root.$emit('checkScore', this.$va.initScoreType(action, voteParams.voteState)); // 积分提醒
        })
        .catch(() => {})
        .then(() => { this.loading[action] = false; });
    },
    // 获取点赞、点踩（或取消）的所需参数
    voteParams(action) {
      return {
        votePosition: 'ProductFile', // 对资源点赞
        votePositionId: this.curDoc.id,
        voteAction: this.$C.vote.action[action], // 这里需要转化成api所需参数
        voteState: !this.curDoc.voteStates[action],
      };
    },
  },
};
</script>

<style></style>
